import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

plt.rcParams['font.sans-serif'] = ['SimHei']

def pltSetter(x,y,xlabel,ylabel,title):
    plt.figure(figsize=(16, 9))
    plt.bar(x, y)
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

# 查看用户收听音乐中各歌手所占比重
def perferAuthorProp(data):
    authors = {}
    for i in data["Author"]:
        if i in authors:
            authors[i] += 1
        else:
            authors[i] = 1
    authors["其他歌手"] = 0
    for i in list(authors.keys()):
        if authors[i] <= 3:
            authors.pop(i)
            authors["其他歌手"] += 1
    plt.title("音乐类型喜好比重")
    plt.pie(authors.values(), labels=authors.keys(), autopct="%.1f%%")
    plt.show()

# 查看用户收听音乐的分类所占比重
def perferTypeProp(data):
    types = {}
    for i in data["Type"]:
        if i in types:
            types[i]+=1
        else:
            types[i]=1
    plt.title("音乐类型喜好比重")
    plt.pie(types.values(),labels=types.keys(),autopct="%.1f%%")
    plt.show()

# 查看用户收听音乐次数的频数直方图
def perferByFrequency(data):
    height = np.array(data["Time"])
    bins = range(0,200,10)
    plt.figure(figsize=(16, 9))
    plt.title("收听次数分布")
    plt.xlabel("收听次数")
    plt.ylabel("频数")
    plt.hist(height,bins=bins)
    plt.show()

# 查看用户收听次数最多的音乐
def perferByTime(data):
    Top10 = data.loc[data["Id"]<=10]
    pltSetter(Top10["Name"],Top10["Time"],"歌曲名称","收听次数","喜好音乐Top10")
    plt.xticks(rotation=10)
    plt.show()

# 查看用户对于某个歌手的作品的收听喜好
def perferByAuthor(data,author):
    x = np.array(data.loc[data["Author"] == author]["Name"])
    y = np.array(data.loc[data["Author"] == author]["Time"])
    pltSetter(x,y,"歌曲名称","收听次数","用户对于"+author+"的收听喜好")
    plt.show()

# 查看用户对不同歌手的音乐收听情况
def perferAuthorTime(data):
    authors = {}
    for i in data["Author"]:
        if i not in authors:
            authors[i] = 0
    for i in range(1,100):
        authors[data.loc[data["Id"]==i].iat[0,2]] += data.loc[data["Id"]==i].iat[0,3]
    pltSetter(authors.keys(), authors.values(), "歌手", "收听总次数", "各歌手收听情况")
    plt.xticks(rotation=10)
    plt.show()



data = pd.read_csv('./music.csv',encoding='gbk')
perferByAuthor(data,"鹿乃")
perferByFrequency(data)
perferByTime(data)
perferTypeProp(data)
perferAuthorProp(data)
perferAuthorTime(data)